#include "mainwindow.h"
#include "../../ui/ui_mainwindow.h"
#include "file_transfer_client.h"
#include "loginwindow.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QInputDialog>

MainWindow::MainWindow(const QString &username, QWidget *parent)
    : QMainWindow(parent),  //  使用 QMainWindow 初始化
      ui(new Ui::MainWindow),
      currentUser(username)
{
    ui->setupUi(this);
    ui->welcomeLabel->setText("欢迎，" + username);

    // // 如果按钮没有在界面中默认显示，强制显示：
    // if (ui->deleteButton)
    //     ui->deleteButton->setVisible(true);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::on_uploadButton_clicked() {
    QString filePath = QFileDialog::getOpenFileName(this, "选择要上传的文件");
    if (filePath.isEmpty()) return;

    FileTransferClient uploader("127.0.0.1", 8888);
    QString error;

    if (uploader.uploadFile(currentUser, filePath, error, this)) {
        QMessageBox::information(this, "上传成功", "文件上传成功！");
    } else {
        QMessageBox::warning(this, "上传失败", error);
    }

}

void MainWindow::on_downloadButton_clicked() {
    FileTransferClient client("127.0.0.1", 8888);
    QString error;
    QStringList files = client.listServerFiles(currentUser, error);

    if (files.isEmpty()) {
        QMessageBox::warning(this, "下载失败", "无法获取文件列表：" + error);
        return;
    }

    bool ok = false;
    QString filename = QInputDialog::getItem(this, "下载文件", "请选择文件：", files, 0, false, &ok);
    if (!ok || filename.isEmpty()) return;

    QString savePath = QFileDialog::getSaveFileName(this, "保存文件为", filename);
    if (savePath.isEmpty()) return;

    if (client.downloadFile(currentUser, filename, savePath, error, this)){
        QMessageBox::information(this, "下载成功", "文件已保存到：" + savePath);
    } else {
        QMessageBox::warning(this, "下载失败", error);
    }
}

void MainWindow::on_deleteButton_clicked() {
    FileTransferClient client("127.0.0.1", 8888);
    QString error;
    QStringList files = client.listServerFiles(currentUser, error);

    if (files.isEmpty()) {
        QMessageBox::warning(this, "删除失败", "你没有可删除的文件或连接失败：" + error);
        return;
    }

    bool ok = false;
    QString filename = QInputDialog::getItem(this, "删除文件", "请选择要删除的文件：", files, 0, false, &ok);
    if (!ok || filename.isEmpty()) return;

    if (client.deleteFile(filename, currentUser, error)) {
        QMessageBox::information(this, "删除成功", "文件已成功删除！");
    } else {
        QMessageBox::warning(this, "删除失败", error);
    }
}

void MainWindow::on_logoutButton_clicked() {
    LoginWindow *login = new LoginWindow();
    login->show();

    this->close();  // 关闭主窗口，回到登录界面
}

void MainWindow::on_logButton_clicked() {
    FileTransferClient client("127.0.0.1", 8888);
    QString error, content = client.getLogContent(currentUser, error);

    if (!error.isEmpty()) {
        QMessageBox::warning(this, "查看失败", error);
        return;
    }

    QMessageBox::information(this, "系统日志", content);
}

